﻿using System;
using System.ServiceModel;
using BigBank.Contracts.Base.V1.Faults;
using BigBank.Contracts.Base.V1.Messages;

namespace BigBank.Contracts.Base.V1
{
    namespace Aspects
    {
        public class SetExecutionTime : BaseServiceAspect
        {
            public SetExecutionTime() : this(-300)
            {
            }

            public SetExecutionTime(int order) : base(order)
            {
            }

            public override void OnPreBaseServiceOperation(ref BaseServiceRequest request)
            {
                request.ExecutionStart = DateTime.UtcNow;
            }

            public override void OnPostBaseServiceOperation(ref BaseServiceRequest request,
                                                            ref BaseServiceResponse response)
            {
                response.ExecutionTime = DateTime.UtcNow.Subtract(request.ExecutionStart);
            }
        }

        public class SetDefaultCorrelationId : BaseServiceAspect
        {
            public SetDefaultCorrelationId() : this(-300)
            {
            }

            public SetDefaultCorrelationId(int order) : base(order)
            {
            }

            public override void OnPreBaseServiceOperation(ref BaseServiceRequest request)
            {
                if (request.CorrelationId == Guid.Empty)
                    request.CorrelationId = Guid.NewGuid();
            }
        }

        public class WrapExceptionsInFaults : BaseServiceAspect
        {
            public WrapExceptionsInFaults() : this(0)
            {
            }

            public WrapExceptionsInFaults(int order) : base(order)
            {
            }

            public override void OnBaseServiceOperationError(ref BaseServiceRequest request, ref Exception exception)
            {
                throw new FaultException<BaseServiceFault>(new BaseServiceFault(), exception.Message);
            }
        }
    }
}